﻿using LightWadf.Core.Result;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace LightWadf.Core.Analyzer
{
    public class DefaultResultParser : IResultAnalyzer
    {
        public async Task Parse(object result, HttpContext context)
        {
            if (result != null)
            {
                if (result is JsonResult)
                {
                    context.Response.ContentType = "application/json";
                    await context.Response.WriteAsync((result as JsonResult).JsonString);
                }
                else if (result is FileResult)
                {
                    FileInfo file = new FileInfo((result as FileResult).FilePath);
                    DateTime lastModified = File.GetLastWriteTimeUtc(file.FullName);
                    DateTime time = Convert.ToDateTime(context.Request.Headers["If-Modified-Since"]);
                    // lastModified 精确到毫秒，time 只精确到秒，会有 1 秒以内的误差
                    if ((lastModified - time).TotalMilliseconds < 1000.0)
                    {
                        context.Response.StatusCode = 304;
                    }
                    else
                    {
                        context.Response.Headers.Add("CacheControl", "max-age=" + int.MaxValue);
                        context.Response.Headers.Add("Last-Modified", file.LastWriteTimeUtc.ToString());
                        await this.WriteFileIntoStream(context.Response, (result as FileResult).FilePath);
                    }
                }
                else if (result is XmlResult)
                {
                    context.Response.ContentType = "application/xml";
                    await context.Response.WriteAsync((result as XmlResult).XmlString);
                }
                else
                {
                    await context.Response.WriteAsync(result.ToString());
                }
            }
            else
            {
                return;
            }
        }

        private async Task WriteFileIntoStream(HttpResponse response, string filePath)
        {
            using(StreamReader reader = new StreamReader(new FileStream(filePath, FileMode.Open)))
            {
                await response.WriteAsync(reader.ReadToEnd());
            }
        }
    }
}